//
//  FYComposeTextView.swift
//  Weibo
//
//  Created by 冯毅 on 16/8/16.
//  Copyright © 2016年 冯毅. All rights reserved.
//

import UIKit
//  自定义UITextView
//  @IBDesignable  实时看到修改后属性的值
class FYComposeTextView: UITextView {

    /*
    // Only override drawRect: if you perform custom drawing.
    // An empty implementation adversely affects performance during animation.
    override func drawRect(rect: CGRect) {
        // Drawing code
    }
    */
    //  占位label
    private lazy var placeHolderLabel: UILabel = {
        let label = UILabel()
        label.font = UIFont.systemFontOfSize(12)
        label.text = "shit"
        label.textColor = UIColor.lightGrayColor()
        //  多行显示
        label.numberOfLines = 0
        return label
    }()
    
    //  提供外界设置占位文字的属性
    //  @IBInspectable  给xib/sb添加可以设置的属性
    @IBInspectable var placeHolder:String? {
        didSet{
            placeHolderLabel.text = placeHolder
        }
        
    }
    //  重写font
    override var font: UIFont? {
        didSet{
            if font != nil {
                //  当前外界设置Font让占位Label与其同步
                placeHolderLabel.font = font
            }
        }
    }
    //  重写text
    override var text: String? {
        didSet {
            //  根据文本内容显示占位label
            placeHolderLabel.hidden = hasText()
        }
    }
    //  手写代码方式
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //  添加控件设置约束
    private func setupUI() {
        //  监听文字改变的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textChange", name: UITextViewTextDidChangeNotification, object: nil)
        
        addSubview(placeHolderLabel)
        
        //  使用系统约束
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .Width, relatedBy: .Equal, toItem: self, attribute: .Width, multiplier: 1, constant: -10))
        
    }
    
    //  监听文字改变的通知
    @objc private func textChange() {
        placeHolderLabel.hidden = hasText()
    }
    
    //  给子控件设置约束
    override func layoutSubviews() {
        super.layoutSubviews()
        //  设置x,y坐标
        placeHolderLabel.frame.origin.x = 5
        placeHolderLabel.frame.origin.y = 7
    }
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
}
